// Copyright (c) 2022 by Duguang.IO Inc. All Rights Reserved.
// Author: Ethan Liu
// Date: 2022-05-05 13:50:18

package image

import (
	"net/url"
	"strings"

	"github.com/docker/distribution/reference"
)

// Trim 返回不包含tag的镜像名
func Trim(name string) string {
	ref, err := reference.ParseAnyReference(name)
	if err != nil {
		return name
	}
	named, err := reference.ParseNamed(ref.String())
	if err != nil {
		return name
	}
	named = reference.TrimNamed(named)
	return reference.FamiliarName(named)
}

// Expand 返回完整限定的镜像名
func Expand(name string) string {
	ref, err := reference.ParseAnyReference(name)
	if err != nil {
		return name
	}
	named, err := reference.ParseNamed(ref.String())
	if err != nil {
		return name
	}
	named = reference.TagNameOnly(named)
	return named.String()
}

// Match 如果from的镜像名在to list中则返回true，不检查镜像tag
func Match(from string, to ...string) bool {
	from = Trim(from)
	for _, match := range to {
		if from == Trim(match) {
			return true
		}
	}
	return false
}

// MatchTag 如果from的镜像名在to list中则返回true，包含镜像tag
func MatchTag(a, b string) bool {
	return Expand(a) == Expand(b)
}

// MatchHostname 如果镜像主机名匹配则返回true
func MatchHostname(image, hostname string) bool {
	ref, err := reference.ParseAnyReference(image)
	if err != nil {
		return false
	}
	named, err := reference.ParseNamed(ref.String())
	if err != nil {
		return false
	}
	if hostname == "index.docker.io" {
		hostname = "docker.io"
	}
	// 提取域名
	if strings.HasPrefix(hostname, "http://") ||
		strings.HasPrefix(hostname, "https://") {
		parsed, err := url.Parse(hostname)
		if err == nil {
			hostname = parsed.Host
		}
	}
	return reference.Domain(named) == hostname
}

// IsLatest 如果镜像使用latest标签则返回true
func IsLatest(s string) bool {
	return strings.HasSuffix(Expand(s), ":latest")
}
